package com.tron.init;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tron.config.XxlJob.XxlJobConfig;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;

import java.net.HttpCookie;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static org.bouncycastle.asn1.x500.style.RFC4519Style.title;

/**
 * Xxl-Jon 初始化
 * 自动登录
 */
@Configuration
@Data
@Slf4j
public class XxlJobInit implements ApplicationRunner {

    @Autowired
    XxlJobConfig xxlJobConfig;

    public String getCookie() {
        for (int i = 0; i < 3; i++) {
            String cookieStr = xxlJobConfig.getLoginCookie().get("XXL_JOB_LOGIN_IDENTITY");
            if (cookieStr !=null) {
                return "XXL_JOB_LOGIN_IDENTITY="+cookieStr;
            }
            login();
        }
        log.error("get xxl-job cookie error!");
        return "";
    }

    /**
     * 模拟 Xxl-Job 管理端登录
     */
    public void login(){
        System.out.println("你正在执行..........................");
        System.out.println(xxlJobConfig.getAdminAddresses());
        String url=xxlJobConfig.getAdminAddresses()+"login";
        HttpResponse response = HttpRequest.post(url)
                .form("userName",xxlJobConfig.getAdminUsername())
                .form("password",xxlJobConfig.getAdminPassword())
                .execute();
        List<HttpCookie> cookies = response.getCookies();
        Optional<HttpCookie> cookieOpt = cookies.stream()
                .filter(cookie -> cookie.getName().equals("XXL_JOB_LOGIN_IDENTITY")).findFirst();
        if (!cookieOpt.isPresent())
            log.error("Xxl-Job自动登录部署失败!");

        String value = cookieOpt.get().getValue();
        System.out.println(value);
        xxlJobConfig.getLoginCookie().put("XXL_JOB_LOGIN_IDENTITY",value);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("Xxl-Job组件正在初始化...");
        log.info("Xxl-Job组件初始化完成 ==> ?");
    }
}
